<template>
  <Container class="role-edit">
    <div class="container-header title title-center" slot="header">
      {{ title }}
      <Button size="large" class="fl btn-back" icon="ios-arrow-back" @click="jumpPrevPage">返回</Button>
    </div>
    <div class="bgs">
      <Form :label-width="80" class="form" :model="form" ref="form" :rules="rules">
        <FormItem label="政策名称" prop="name">
          <Input
            :maxlength="20"
            class="common-width"
            v-model.trim="form.name"
            placeholder="请输入2-20位字符的政策名称"
          />
        </FormItem>
        <FormItem label="生效时间"  prop='date'>
          <DatePicker
            v-model="form.date"
            type="daterange"
            placeholder="请选择生效时间"
            class="common-width"
          ></DatePicker>
        </FormItem>
        <FormItem label="添加品牌">
          <Select v-model="inputModel" @on-change="onChange" multiple class="common-width">
            <Option
              v-for="item in list.brandList"
              :value="item.brandId"
              :key="item.brandId"
            >{{item.brandName}}</Option>
          </Select>
        </FormItem>
      </Form>
      <div class="table-content">
        <p class="describle" v-if="list.tableInfoList.length<=0">暂时没有添加品牌哦,可以在下面下拉框添中加品牌</p>
        <div v-else>
          <div class="all-content" v-for="(item, idx) in list.tableInfoList" :key="idx">
            <Table border :columns="item.columns" :data="item.data"></Table>
          </div>
        </div>
      </div>
    </div>
    <Loader :status="status" @refresh="getInfo"></Loader>
    <div class="container-footer bg-white" slot="footer">
      <div>
        <Button type="primary" class="mr" size="large" :disabled="isDisabled" @click="onSave">保存</Button>
        <Button type="primary" class="mr" size="large" @click="cancle">取消</Button>
      </div>
    </div>
  </Container>
</template>
<script>
import table from "@/table";
import data from "./edit/RebateEditItemData";
// import editData from "./edit/RebateGetInfoData";
import { formatDate, getOriginData, getTireArr } from "@/util";
export default {
  data() {
    const validateName = (rule, value, callback) => {
      if (value.trim() === "") {
        callback(new Error("请输入政策名称"));
      } else {
        if (value.length < 2) {
          callback(new Error("政策名称在2-20个字之间"));
        }
        callback();
      }
    };
    const validateDate = (rule, value, callback) => {
      if (value[0] === "") {
        callback(new Error("请输入时间"));
      } 
      callback();
    };
    return {
      id: this.$route.query.id || "",
      title: "",
      status: "pass",
      isDisabled: false,
      inputModel: [],
      form: {
        name: "",
        brandId: "",
        date: []
      },
      rules: {
        name: [{ required: true, validator: validateName, trigger: "blur" }],
        date: [{ required: true, validator: validateDate, trigger: "blur" }]
      },
      options: {
        tableHeight: 300
      },
      tire_sizeArr: [],
      sizeList: [],
      storeType: [],
      list: data,
      policyItems: {}
      // editData: editData
    };
  },
  mounted() {
    this.initTable();
    this.$refs.form.resetFields();
    if (this.$route.query.id) {
      this.id = this.$route.query.id;
      this.title = "编辑政策";
    } else {
      this.title = "新增政策";
      this.list.tableInfoList = [];
    }
    this.initData();
  },
  destroyed() {
    this.$bus.$off();
  },
  methods: {
    ...table,
    async initData() {
      await this.getStoreList();
      await this.getTireData();
      await this.getBrandList();
      await this.getInfo();
    },
    getBrandList() {
      this.$ajaxGet("/product/common/supplier_brand").then(data => {
        this.list.brandList = data;
      });
    },
    getStoreList() {
     return this.$ajaxGet("storeType/findAll").then(data => {
        this.storeType = data.map(item => {
          let obj = { storeTypeId: item.id, storeTypeName: item.name };
          return obj;
        });
      });
    },
    getTireData() {
     return getTireArr().then(data => {
        this.tire_sizeArr = data.data.tire_rim
          .filter(item => item.val)
          .map(item => {
            return {
              value: item.val
            };
          });
        this.tire_sizeArr.forEach(v => {
          this.sizeList.push(v["value"]);
        });
      });
    },
    getInfo() {
      if (!this.id) return;
      this.status = "loading";
      return  this.$ajaxGet(`/setting/rebate_policy/detail/${this.id}`)
        .then(data => {
          const {
            policyName,
            beginDate,
            endDate,
            brandList,
            policyItems
          } = data;
          this.form.name = policyName;
          this.form.date = [formatDate(beginDate), formatDate(endDate)];
          this.inputModel = brandList.map(item => {
            return item.brandId;
          });
          this.policyItems = policyItems;
          setTimeout(()=>{
            this.status = "pass";
          },1000)
        })
        .catch(() => {
          this.status = "error";
        });
    },
    getTableData() {
      this.list.tableInfoList = this.list.tableInfoList.map(item => {
        item.columns = [];
        item.columns.push({
          title: item.brandName,
          key: "storeTypeName",
          align: 'left',
          fixed: "left",
          width: 100
        });
        let size = item.sizeList.map(s => {
          return {
            title: `${s}寸`,
            key: s,
            align: 'left',
            minWidth: 90,
            render: (h, p) => {
              return h("InputNumber", {
                props: {
                  min: 0,
                  max: 1000,
                  size: "small",
                  value: p.row[s]
                },
                on: {
                  "on-change": e => {
                    p.row[s] = e;
                    this.$set(item.data, p.index, p.row);
                  }
                }
              });
            }
          };
        });
        item.columns = item.columns.concat(size);
        let dataSource = this.policyItems;
        if (!item.data || item.data.length == 0) {
          item.data = [];
          item.data = item.storeType.map(e => {
            let obj = {
              storeTypeName: e.storeTypeName,
              storeTypeId: e.storeTypeId
            };
            item.sizeList.forEach(s => {
              if (this.id) {
                let objKey = `${item.brandId}_${e.storeTypeId}_${s}`;
                obj[s] = dataSource[objKey] || 0;
              } else {
                obj[s] = 0;
              }
            });
            return obj;
          });
        }
        return item;
      });
    },
    onChange(s) {
      // s.map(item => {
      //   let b = this.list.brandList.find(a => {
      //     return item == a.brandId;
      //   });
      //   let c = this.list.tableInfoList.find(v => {
      //     return b.brandId == v.brandId;
      //   });
      //   if (!c) {
      //     this.list.tableInfoList.push(b);
      //   }
      // });
      let all = getOriginData(this.list.brandList).map(item => {
        const { brandId, brandName, id } = item;
        item.data = [];
        item.columns = [];
        item.sizeList = this.sizeList;
        item.storeType = this.storeType;
        return item;
      });
      this.list.tableInfoList = all.filter(e => {
        let v = s.find(i => i == e.brandId);
        if (!v) {
          e.data = [];
        }
        return v;
      });
      setTimeout(() => {
        this.getTableData();
      }, 20);
    },
    getParamList() {
      return this.list.tableInfoList.map(item => {
        let itemObj = {};
        let arr = [];
        item.data.forEach(d => {
          let storeTypeId = d.storeTypeId;
          let storeTypeName = d.storeTypeName;
          let keyArr = Object.keys(d);
          let keyArr1 = keyArr.filter(
            e =>
              e != "storeTypeName" &&
              e != "storeTypeId" &&
              e != "_index" &&
              e != "_rowKey"
          );
          let objKey = keyArr1.map(v => {
            let obj = {
              tiresRim: v,
              rebate: d[v],
              storeTypeId: storeTypeId,
              storeTypeName: storeTypeName,
              brandId: item.brandId,
              brandName: item.brandName
            };
            return obj;
          });
          arr = arr.concat(objKey);
        });
        itemObj = arr;
        return itemObj;
      });
    },
    onSave() {
      if (this.isDisabled) return;
      this.$refs["form"].validate(valid => {
        if (valid) {
          let arr = this.getParamList();
          var newArr = [];
          arr.forEach((s, i) => {
            newArr = newArr.concat(arr[i]);
          });
          this.isDisabled = true;
          let url = this.id
            ? "/setting/rebate_policy/modify"
            : "/setting/rebate_policy/save";
          let text = this.id ? "编辑" : "新增";
          let param = {
            policyName: this.form.name || "",
             id:this.id ? this.id:'',
            rebatePolicyItems: newArr || []
          };
          if (this.form.date[0])
            param.beginDate = formatDate(this.form.date[0]) + " 00:00:00";
          if (this.form.date[1])
            param.endDate = formatDate(this.form.date[1]) + " 23:59:59";
          this.$jsonPost(url, param)
            .then(data => {
              this.$Notice.success({
                title: `${text}成功`
              });
              this.$router.push("/policy/rebate/list");
            })
            .catch(() => {
              this.isDisabled = false;
            });
        }
      });
    },
    cancle(){
      this.$router.back();
    },
    jumpPrevPage() {
      this.$router.back();
    }
  }
};
</script>
